package db

import (
	"cr.org/config"
	"fmt"
	"github.com/sirupsen/logrus"
	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var db *gorm.DB

func GetDB() *gorm.DB {
	return db
}

func InitDB() {
	var logMode logger.Interface
	// 只有当日志级别时debug时才打印sql，
	if config.GlobalConfig.SqlLog {
		logMode = logger.Default.LogMode(logger.Info)
	} else {
		logMode = logger.Default.LogMode(logger.Silent)
	}
	var err error
	switch config.GlobalConfig.DB {
	case "sqlite":
		db, err = gorm.Open(sqlite.Open(config.GlobalConfig.Sqlite.File), &gorm.Config{
			Logger: logMode,
		})
	case "pgsql":
		dsn := fmt.Sprintf("user=%s password=%s dbname=%s port=%d host=%s sslmode=disable TimeZone=Asia/Shanghai",
			config.GlobalConfig.Pgsql.Username,
			config.GlobalConfig.Pgsql.Password,
			config.GlobalConfig.Pgsql.DBName,
			config.GlobalConfig.Pgsql.Port,
			config.GlobalConfig.Pgsql.Addr,
		)
		db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{
			Logger: logMode,
			// SkipDefaultTransaction: true, // 跳过事务控制
			//CreateBatchSize: 500, //创建数据时每一批数据的大小

		})
	default:
		logrus.Panic("未定义的数据库类型")
	}
	if err != nil {
		panic(fmt.Errorf("连接数据库异常: %v", err.Error()))
	}

}
